import React from 'react'
import { render as renderAmis, RenderOptions } from 'amis'
import 'amis/lib/themes/cxd.css'
import { Schema } from 'amis/lib/types'
import { RootRenderProps } from 'amis-core/lib/Root'
import DefaultFetcher from '@/components/amis/DefaultFetcher'
import copy from 'copy-to-clipboard'
import { ToastConf, ToastLevel } from 'amis-core/lib/types'
import { message } from 'antd'

class AmisRender {
	private readonly fetcher = new DefaultFetcher()
	// amis 环境配置
	readonly options = {
		// 下面三个接口必须实现
		fetcher: this.fetcher.fetch,
		isCancel: this.fetcher.isCancel,
		updateLocation: (location: any, replace?: boolean) => {},
		copy: (content: string) => {
			copy(content)
			message.success('内容已复制到粘贴板')
		},
		alert: (msg: string): void => {
			alert(msg)
		},
		notify: (type: ToastLevel, msg: any, conf?: ToastConf): void => {
			if (type == 'info') {
				message.info(msg)
				return
			}
			if (type == 'success') {
				message.success(msg)
				return
			}
			if (type == 'warning') {
				message.warning(msg)
				return
			}
			if (type == 'error') {
				message.error(msg)
				return
			}
			message.info(msg)
			return
		},
		theme: 'antd',
	} as RenderOptions

	constructor() {}

	render = (schema: Schema, props?: RootRenderProps, options?: RenderOptions, pathPrefix?: string): JSX.Element => {
		const realOptions = options ? options : this.options
		return (
			<>
				{renderAmis(
					// 这里是 amisApp 的 Json 配置。
					schema,
					props,
					realOptions,
					pathPrefix,
				)}
			</>
		)
	}
}

export default new AmisRender()
